<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 题库数据
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-lx-add"
                    class="handle-del mr10"
                    @click="handleAdd"
                >添加</el-button>
                <el-input v-model="query.content" placeholder="题干" class="handle-input mr10"></el-input>
                <el-input v-model="query.score" placeholder="分值" class="handle-input mr10"></el-input>
                <el-select v-model="query.questionType" slot="prepend" clearable placeholder="题型" class="handle-input mr10">
                    <el-option label="单选" value="单选"></el-option>
                    <el-option label="多选" value="多选"></el-option>
                    <el-option label="判断" value="判断"></el-option>
                    <el-option label="简答" value="简答"></el-option>
                </el-select>
                <el-input v-model="query.type" placeholder="类型" class="handle-input mr10"></el-input>
                <el-select v-model="query.difficulty" slot="prepend" clearable placeholder="难度" class="handle-input mr10">
                    <el-option label="简单" value="0"></el-option>
                    <el-option label="中等" value="1"></el-option>
                    <el-option label="困难" value="2"></el-option>
                </el-select>
                <el-button type="primary" style="margin-right: 5px;" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <download-excel
                    class="export-excel-wrapper"
                    :data="selectData"
                    :fields="json_fields"
                    :header="title"
                    name="题库数据.xls"
                    >
                    <el-button type="primary" style="margin-right: 5px;" icon="el-icon-lx-down" @click="handleExport">导出</el-button>
                </download-excel>
                <download-excel
                    class="export-excel-wrapper"
                    :data="allData"
                    :fields="json_fields"
                    :header="title"
                    name="题库数据(全部).xls"
                    >
                    <el-button type="primary" icon="el-icon-lx-down" @click="handleExportAll">全部导出</el-button>
                </download-excel>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="content" label="题干"></el-table-column>
                <el-table-column prop="score" sortable label="分值"></el-table-column>
                <el-table-column prop="questionType" label="题型"></el-table-column>
                
                <el-table-column label="选项"  width="200">
                    <template slot-scope="scope">
                        <p :key="item" v-for = "item in scope.row.selection">{{item.select}} : {{ item.selectContent }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="answer" label="答案">
                    <template slot-scope="scope">
                        <el-tag type="success">{{scope.row.answer}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="analysis" label="解析"></el-table-column>
                <el-table-column prop="remark" label="备注"></el-table-column>
                <el-table-column prop="type" label="类型"></el-table-column>
                <el-table-column label="难度">
                    <template slot-scope="scope">{{scope.row.difficulty==0 ? '简单':(scope.row.difficulty==1 ? '中等':(scope.row.difficulty==2 ? '困难':'未知'))}}</template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">{{scope.row.status==0 ? '有效':(scope.row.status==1 ? '无效':'无')}}</template>
                </el-table-column>
                <el-table-column label="正确率">
                    <template slot-scope="scope">{{scope.row.writeCnt == 0 ? 0 : (scope.row.correctCnt/scope.row.writeCnt).toFixed(3)}}</template>
                </el-table-column>

                <el-table-column prop="createTime" label="创建时间"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.current"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="题干">
                    <el-input v-model="form.content"></el-input>
                </el-form-item>
                <!-- <el-form-item label="选项">
                    <el-input v-model="form.selection"></el-input>
                </el-form-item> -->
                <el-form-item label="答案">
                    <el-input v-model="form.answer"></el-input>
                </el-form-item>
                <el-form-item label="解析">
                    <el-input v-model="form.analysis"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark"></el-input>
                </el-form-item>
                <el-form-item label="分值">
                    <el-input v-model="form.score"></el-input>
                </el-form-item>
                <el-form-item label="题型">
                    <el-select v-model="form.questionType" clearable placeholder="请选择" class="formSelect">
                        <el-option label="单选题" value="单选题"></el-option>
                        <el-option label="多选题" value="多选题"></el-option>
                        <el-option label="判断题" value="判断题"></el-option>
                        <el-option label="简答题" value="简答题"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="类型">
                    <el-input v-model="form.type"></el-input>
                </el-form-item>
                <el-form-item label="难度">
                    <el-select v-model="form.difficulty" clearable placeholder="请选择" class="formSelect">
                        <el-option label="简单" value="0"></el-option>
                        <el-option label="中等" value="1"></el-option>
                        <el-option label="困难" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="form.status" clearable placeholder="请选择" class="formSelect">
                        <el-option label="有效" value="0"></el-option>
                        <el-option label="无效" value="1"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item
                v-for="(item, index) in form.selection"
                :label="'选项' + index"
                :key="item.select"
                :prop="'selection.' + index + '.select'"
                >
                    <el-input v-model="item.select" placeholder="选项标签（比如A）"></el-input>
                    <el-input v-model="item.selectContent" placeholder="选项内容"></el-input>
                    
                    <el-button @click.prevent="removeSelect1(item)">删除</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">修 改</el-button>
                <el-button @click="addSelect1">新增选项</el-button>
            </span>
        </el-dialog>

        <!-- 添加弹出框 -->
        <el-dialog title="添加题目" :visible.sync="addVisible" width="30%">
            <el-form ref="addform" :model="addform" label-width="70px">
                <el-form-item label="题干">
                    <el-input v-model="addform.content"></el-input>
                </el-form-item>
                
                <el-form-item label="答案">
                    <el-input v-model="addform.answer"></el-input>
                </el-form-item>
                <el-form-item label="解析">
                    <el-input v-model="addform.analysis"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addform.remark"></el-input>
                </el-form-item>
                <el-form-item label="分值">
                    <el-input v-model="addform.score"></el-input>
                </el-form-item>
                <el-form-item label="题型">
                    <el-select v-model="addform.questionType" clearable placeholder="请选择" class="formSelect">
                        <el-option label="单选题" value="单选题"></el-option>
                        <el-option label="多选题" value="多选题"></el-option>
                        <el-option label="判断题" value="判断题"></el-option>
                        <el-option label="简答题" value="简答题"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="类型">
                    <el-input v-model="addform.type" placeholder="如党史知识"></el-input>
                </el-form-item>
                <el-form-item label="难度">
                    <el-select v-model="addform.difficulty" clearable placeholder="请选择" class="formSelect">
                        <el-option label="简单" value="0"></el-option>
                        <el-option label="中等" value="1"></el-option>
                        <el-option label="困难" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="addform.status" clearable placeholder="请选择" class="formSelect">
                        <el-option label="有效" value="0"></el-option>
                        <el-option label="无效" value="1"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item
                v-for="(item, index) in addform.selection"
                :label="'选项' + index"
                :key="item.select"
                :prop="'selection.' + index + '.select'"
                >
                    <el-input v-model="item.select" placeholder="选项标签（比如A）"></el-input>
                    <el-input v-model="item.selectContent" placeholder="选项内容"></el-input>
                    
                    <el-button @click.prevent="removeSelect(item)">删除</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">添 加</el-button>
                <el-button @click="addSelect">新增选项</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getQuestionList, deleteQuestion, addQuestion, updateQuestion, getAllQuestionList } from '../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                current: 1,
                pageSize: 10,
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            addVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            title:'题库数据',
            allData:'',
            selectData:'',
            json_fields: {
                'id': 'id',
                '题干': 'content',
                '选项': 'selection',
                '答案': 'answer',
                '解析': 'analysis',
                '备注': 'remark',
                '分值': 'score',
                '题型': 'questionType',
                '类型': 'type',
                '难度': 'difficulty',
                '状态': 'status',
                '创建时间': 'createTime',
                '更新时间': 'updateTime'
            },
            addform: {
                'content': '',
                'selection': [{
                    select: '',
                    selectContent:''
                }],
                'answer':'',
                'analysis':'',
                'remark':'',
                'score': '',
                'questionType': '',
                'type': '',
                'difficulty': '',
                'status': '',
            }
        };
    },
    created() {
        this.getData();
        getAllQuestionList().then(res => {
            console.log(res)
            this.allData=res.data
            for(var i=0;i<this.allData.length;i++){
                this.allData[i].difficulty=this.allData[i].difficulty == 0 ? '简单' : (this.allData[i].difficulty == 1 ? '中等' : (this.allData[i].difficulty == 2 ? '困难' : '未知'))
                this.allData[i].status=this.allData[i].status == 1 ? '无效' : '有效'
                var temp=''
                for(var j=0;j<this.allData[i].selection.length;++j){
                    temp = temp + this.allData[i].selection[j].select + ':' + this.allData[i].selection[j].selectContent + '\n'
                }
                this.allData[i].selection=temp
            }
            
            console.log(this.allData)
        }).catch(err => {
            this.$message.error('加载题库数据失败！')
        })
    },
    methods: {
        getData() {
            getQuestionList(this.query).then(response => {
                if(response.code != 0){
                    this.$message.error(response.message)
                }else{
                    let res = response.data
                    this.tableData = res.records;
                    this.pageTotal = res.total;
                }
            });
        },
        removeSelect(item) {
            var index = this.addform.selection.indexOf(item)
            if (index !== -1) {
                this.addform.selection.splice(index, 1)
            }
        },
        removeSelect1(item) {
            var index = this.form.selection.indexOf(item)
            if (index !== -1) {
                this.form.selection.splice(index, 1)
            }
        },
        addSelect() {
            this.addform.selection.push({
                select: '',
                selectContent: ''
            });
        },
        addSelect1() {
            this.form.selection.push({
                select: '',
                selectContent: ''
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },
        //导出表格
        handleExport() {
            console.log('导出表格')
        },
        //添加题目
        saveAdd() {
            addQuestion(this.addform).then(res => {
                console.log(res)
                if(res.code!=0){
                    this.$message.error(res.message)
                }else{
                    this.$message.success('添加成功!')
                    this.addVisible=false
                    this.getData() 
                }
                
            }).catch(err => {
                this.$message.error('添加失败，请检查信息是否正确!')
            })
        },
        handleAdd() {
            this.addVisible=true
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    deleteQuestion(row).then( res => {
                        if(res.code!=0){
                            this.$message.error(res.message)
                        }else{
                            this.$message.success('删除成功');
                            this.tableData.splice(index, 1);
                            this.pageTotal-=1
                        }
                    }).then(()=>{
                        
                    }).catch(err => {
                        this.$message.error('删除失败！')
                    })
                })
                .catch(() => {});
        },
        deepClone(target) {
            if (typeof target === 'object' && target !== null) {
                return JSON.parse(JSON.stringify(target));
            } else {
                return target;
            }
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            const tmp = this.deepClone(val)
            console.log(tmp)
            for(var i=0;i<tmp.length;i++){
                tmp[i].difficulty=tmp[i].difficulty == 0 ? '简单' : (tmp[i].difficulty == 1 ? '中等' : (tmp[i].difficulty == 2 ? '困难' : '未知'))
                tmp[i].status=tmp[i].status == 1 ? '无效' : '有效'
                var temp=''
                for(var j=0;j<tmp[i].selection.length;++j){
                    temp = temp + tmp[i].selection[j].select + ':' + tmp[i].selection[j].selectContent + '\n'
                }
                tmp[i].selection=temp
            }
            console.log(tmp)
            this.selectData=tmp
            console.log(this.selectData)
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.form.difficulty=this.form.difficulty+''
            this.form.status=this.form.status+''
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            updateQuestion(this.form).then(res => {
                if(res.code!=0){
                    this.$message.error(res.message)
                    this.getData()
                }else{
                    this.$message.success(`修改第 ${this.idx + 1} 行成功!`);
                    this.$set(this.tableData, this.idx, this.form);
                }
                
            }).catch(err => {
                this.$message.error('修改第 ${this.idx + 1} 行失败!')
            })
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
    display: flex;
}

.handle-select {
    width: 120px;
}

.formSelect {
    width: 100%;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
